<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="预约状态" prop="status" style="width: 200px">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择预约状态"
          clearable
        >
          <el-option
            v-for="dict in reservation_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        label="预约人姓名"
        prop="applicantName"
        label-width="100px"
        style="width: 250px"
      >
        <el-input
          v-model="queryParams.applicantName"
          placeholder="请输入预约人姓名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="phone" style="width: 250px">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="预约时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeAppointmentTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="default"
          plain
          @click="resetQuery"
          >全部</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          @click="handleAppointmentTypeChange(1)"
          v-hasPermi="['le:registration:query']"
          >探访预约</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          @click="handleAppointmentTypeChange(0)"
          v-hasPermi="['le:registration:query']"
          >参观预约</el-button
        >
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['le:registration:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['le:registration:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['le:registration:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['le:registration:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="registrationList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="预约类型" align="center" prop="appointmentType">
        <template #default="scope">
          <dict-tag
            :options="appointment_type"
            :value="scope.row.appointmentType"
          />
        </template>
      </el-table-column>
      <!-- <el-table-column label="微信登录账号外键" align="center" prop="wxUserId" /> -->
      <el-table-column label="预约人姓名" align="center" prop="applicantName" />
      <el-table-column label="手机号" align="center" prop="phone" />
      <el-table-column label="老人姓名" align="center" prop="elderlyId">
        <template #default="scope">
          <span v-for="item in elderlyList" :key="item.id">
            <span v-if="item.id == scope.row.elderlyId">
              {{ item.name }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="预约时间"
        align="center"
        prop="appointmentTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.appointmentTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="creator">
        <template #default="scope">
          <span v-for="item in userList" :key="item.id">
            <span v-if="item.userId == scope.row.creator">
              {{ item.nickName }}
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="reservation_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <!-- 到院按钮：有arrivalTime则灰色禁用，无则可点击 -->
          <!-- 关键：有值则禁用 -->
          <!-- 直接用中文字符串匹配 -->
          <el-button
            link
            type="primary"
            icon="Clock"
            @click="handleArrival(scope.row)"
            :disabled="
              !(
                scope.row.arrivalTime === null ||
                scope.row.arrivalTime === undefined
              ) || scope.row.status !== '0'
            "
            v-hasPermi="['le:registration:edit']"
          >
            到院
          </el-button>
          <!-- <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['le:registration:edit']">修改</el-button> -->
          <!-- <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['le:registration:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预约登记对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="registrationRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="预约类型" prop="appointmentType">
          <el-select
            v-model="form.appointmentType"
            placeholder="请选择预约类型"
          >
            <el-option
              v-for="dict in appointment_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="微信登录账号外键" prop="wxUserId">
          <el-input
            v-model="form.wxUserId"
            placeholder="请输入微信登录账号外键"
          />
        </el-form-item>
        <el-form-item label="预约人姓名" prop="applicantName">
          <el-input
            v-model="form.applicantName"
            placeholder="请输入预约人姓名"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="老人姓名" prop="elderlyId">
          <el-input v-model="form.elderlyId" placeholder="请输入老人外键编号" />
        </el-form-item>
        <el-form-item label="预约时间" prop="appointmentTime">
          <el-date-picker
            clearable
            v-model="form.appointmentTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择预约时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="创建人" prop="creator">
          <el-input v-model="form.creator" placeholder="请输入创建人" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in reservation_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      title="登记到院时间"
      v-model="arrivalOpen"
      width="300px"
      append-to-body
    >
      <el-form
        ref="arrivalRef"
        :model="arrivalForm"
        :rules="arrivalRules"
        label-width="80px"
      >
        <!-- 仅保留到院时间选择器（支持日期+时分秒） -->
        <!-- 关键：支持选择时分秒 -->
        <!-- 与数据库时间格式对齐 -->
        <el-form-item label="到院时间" prop="arrivalTime">
          <el-date-picker
            clearable
            v-model="arrivalForm.arrivalTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择到院时间"
            style="width: 100%"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitArrival">确 定</el-button>
          <el-button @click="arrivalOpen = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Registration">
import {
  listRegistration,
  getRegistration,
  delRegistration,
  addRegistration,
  updateRegistrationArrivalTime,
} from "@/api/le/registration";

const { proxy } = getCurrentInstance();
const { appointment_type, reservation_status } = proxy.useDict(
  "appointment_type",
  "reservation_status"
);

const registrationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAppointmentTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    appointmentType: null,
    applicantName: null,
    phone: null,
    appointmentTime: null,
    createTime: null,
    arrivalTime: null,
    status: null,
  },
  rules: {
    appointmentType: [
      { required: true, message: "预约类型不能为空", trigger: "change" },
    ],
    wxUserId: [
      { required: true, message: "微信登录账号外键不能为空", trigger: "blur" },
    ],
    applicantName: [
      { required: true, message: "预约人姓名不能为空", trigger: "blur" },
    ],
    phone: [{ required: true, message: "手机号不能为空", trigger: "blur" }],
    elderlyId: [
      { required: true, message: "老人外键编号不能为空", trigger: "blur" },
    ],
    appointmentTime: [
      { required: true, message: "预约时间不能为空", trigger: "blur" },
    ],
    creator: [{ required: true, message: "创建人不能为空", trigger: "blur" }],
    createTime: [
      { required: true, message: "创建时间不能为空", trigger: "blur" },
    ],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
  },
});

const { queryParams, form, rules } = toRefs(data);

/** 查询预约登记列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeAppointmentTime && "" != daterangeAppointmentTime) {
    queryParams.value.params["beginAppointmentTime"] =
      daterangeAppointmentTime.value[0];
    queryParams.value.params["endAppointmentTime"] =
      daterangeAppointmentTime.value[1];
  }
  listRegistration(queryParams.value).then((response) => {
    registrationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    appointmentType: null,
    wxUserId: null,
    applicantName: null,
    phone: null,
    elderlyId: null,
    appointmentTime: null,
    creator: null,
    createTime: null,
    status: null,
    arrivalTime: null,
    isDeleted: null,
    extraField1: null,
    extraField2: null,
  };
  proxy.resetForm("registrationRef");
}

// 新增：到院时间编辑对话框相关数据
const arrivalOpen = ref(false); // 到院对话框显隐
const arrivalForm = reactive({
  // 到院表单（仅存id和到院时间）
  id: null,
  arrivalTime: null,
});
// 新增：到院表单校验规则（仅必填）
const arrivalRules = reactive({
  arrivalTime: [
    { required: true, message: "到院时间不能为空", trigger: "blur" },
  ],
});
// 新增：获取到院表单的ref（用于校验）
const arrivalRef = ref(null);

// 原有data、toRefs、getList等函数不变...

/** 新增：到院按钮点击事件 */
function handleArrival(row) {
  // 重置到院表单
  arrivalForm.id = row.id; // 携带当前行的主键ID（用于后端更新）
  arrivalForm.arrivalTime = null; // 清空历史选择
  // 重置表单校验状态
  if (arrivalRef.value) {
    arrivalRef.value.resetFields();
  }
  // 打开到院对话框
  arrivalOpen.value = true;
}

/** 新增：提交到院时间 */
function submitArrival() {
  // 1. 表单校验（保持原有逻辑）
  arrivalRef.value.validate((valid) => {
    if (valid) {
      // 2. 构造请求参数：仅传递后端需要的字段（id + arrivalTime），避免冗余字段干扰
      const submitData = {
        id: arrivalForm.id, // 必须：用于后端定位要修改的预约记录
        arrivalTime: arrivalForm.arrivalTime, // 必须：要更新的到院时间
        // 注意：不传递其他字段（如appointmentType、applicantName等），防止覆盖数据库原有数据
      };

      // 3. 调用后端 updateRegistrationArrivalTime 接口
      updateRegistrationArrivalTime(submitData)
        .then((response) => {
          // 4. 接口调用成功后的处理（保持原有逻辑）
          proxy.$modal.msgSuccess("到院时间登记成功");
          arrivalOpen.value = false; // 关闭到院时间对话框
          getList(); // 刷新列表，实时更新表格中“到院”按钮的禁用状态
        })
        .catch((error) => {
          // 5. 新增：接口调用失败的异常处理（增强用户体验）
          proxy.$modal.msgError(
            error.response?.data?.msg || "到院时间登记失败，请重试"
          );
        });
    }
  });
}

function handleAppointmentTypeChange(appointmentType) {
  queryParams.value.appointmentType = appointmentType;
  handleQuery();
}
/** 搜索按钮操作 */
function handleQuery() {
  console.log(queryParams.value.appointmentType);
  queryParams.value.pageNum = 1;
  getList();
}


/** 重置按钮操作 */
function resetQuery() {
  daterangeAppointmentTime.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.appointmentType = null;
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加预约登记";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getRegistration(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改预约登记";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["registrationRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateRegistration(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addRegistration(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除预约登记编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delRegistration(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "le/registration/export",
    {
      ...queryParams.value,
    },
    `registration_${new Date().getTime()}.xlsx`
  );
}

//获取老人列表
import { listElderly } from "@/api/le/elderly";
const elderlyList = ref([]);
const getElderlyList = () => {
  listElderly({
    pageNum: 1,
    pageSize: 1000,
  }).then((response) => {
    elderlyList.value = response.rows;
  });
};
//获取用户列表
import { listUser } from "@/api/system/user";
const userList = ref([]);
const getuserList = () => {
  listUser({
    pageNum: 1,
    pageSize: 1000,
  }).then((response) => {
    userList.value = response.rows;
  });
};

getList();
getElderlyList();
getuserList();

</script>
